#!/usr/bin/env python2 
#-*- coding:utf-8 -*-

import json
from flask import Blueprint
from Ump import webutil
from Ump.jsonify import data2json
from Ump.objs.db.manager import DBManager
from base import BaseHandler


dbm = DBManager()


class Query(BaseHandler):

    def post(self):
        custom_data = self.custom_data
        msg = custom_data['msg']
        if not isinstance(msg, dict):
            msg = json.loads(msg)
        return self._POST(msg)

    def _POST(self, msg):
        body = msg.values()[0]
        body['reply'] = {}

        params = msg.values()[0].get('params', {})

        result = webutil.ui_return(dbm.query, params)
        result = json.loads(result[0])
        records = result.get('records')
        reply = result.get('reply', {}) 

        body['reply'] = reply 
        body['records'] = records

        result = data2json(msg)
        return result

app = Blueprint('query', __name__, template_folder='templates')
app.add_url_rule('/db', view_func=Query.as_view('query'))
